package com.linx.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linx.common.core.utils.MapstructUtils;
import com.linx.common.core.utils.StringUtils;
import com.linx.common.mybatis.core.page.PageQuery;
import com.linx.common.mybatis.core.page.TableDataInfo;
import com.linx.system.domain.SysUser;
import com.linx.system.domain.SysUserGroup;
import com.linx.system.domain.bo.SysUserGroupBo;
import com.linx.system.domain.vo.SysUserGroupVo;
import com.linx.system.mapper.SysUserGroupMapper;
import com.linx.system.mapper.SysUserMapper;
import com.linx.system.service.ISysUserGroupService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 人员群组Service业务层处理
 *
 * @author 泽智科技
 * @date 2024-10-02
 */
@RequiredArgsConstructor
@Service
public class SysUserGroupServiceImpl implements ISysUserGroupService {

    private final SysUserGroupMapper sysUserGroupMapper;

    private final SysUserMapper sysUserMapper;

    /**
     * 查询人员群组
     *
     * @param userGroupId 主键
     * @return 人员群组
     */
    @Override
    public SysUserGroupVo queryById(Long userGroupId){
        SysUserGroupVo userGroupVo = sysUserGroupMapper.selectVoById(userGroupId);
        if (userGroupVo == null){
            throw new IllegalArgumentException("用户群组不存在");
        }

        // 查询组用户列表
        List<SysUser> userList = sysUserMapper.selectList(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUserGroupId, userGroupId));
        userGroupVo.setUserIds(userList.stream().map(SysUser::getUserId).toList());

        return userGroupVo;
    }

    /**
     * 分页查询人员群组列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 人员群组分页列表
     */
    @Override
    public TableDataInfo<SysUserGroupVo> queryPageList(SysUserGroupBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserGroup> lqw = buildQueryWrapper(bo);
        Page<SysUserGroupVo> result = sysUserGroupMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(userGroupVo -> {
            Long userNum = sysUserMapper.selectCount(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUserGroupId, userGroupVo.getUserGroupId()));
            userGroupVo.setUserNum(userNum);
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的人员群组列表
     *
     * @param bo 查询条件
     * @return 人员群组列表
     */
    @Override
    public List<SysUserGroupVo> queryList(SysUserGroupBo bo) {
        LambdaQueryWrapper<SysUserGroup> lqw = buildQueryWrapper(bo);
        return sysUserGroupMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserGroup> buildQueryWrapper(SysUserGroupBo bo) {
        LambdaQueryWrapper<SysUserGroup> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getGroupName()), SysUserGroup::getGroupName, bo.getGroupName());
        lqw.orderBy(true,false,SysUserGroup::getCreateTime);
        return lqw;
    }

    /**
     * 新增人员群组
     *
     * @param form 人员群组
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysUserGroupBo form) {
        SysUserGroup userGroup = MapstructUtils.convert(form, SysUserGroup.class);
        validEntityBeforeSave(userGroup);
        boolean flag = sysUserGroupMapper.insert(userGroup) > 0;
        if (flag && userGroup != null) {
            form.setUserGroupId(userGroup.getUserGroupId());

            // 修改用户分组
            if (CollectionUtils.isNotEmpty(form.getUserIds())) {
                List<SysUser> userInfoList = sysUserMapper.selectBatchIds(form.getUserIds());
                userInfoList.forEach(userInfo -> userInfo.setUserGroupId(userGroup.getUserGroupId()));
                flag = sysUserMapper.updateBatchById(userInfoList);
            }
        }

        return flag;
    }

    /**
     * 修改人员群组
     *
     * @param form 人员群组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByBo(SysUserGroupBo form) {
        SysUserGroup update = MapstructUtils.convert(form, SysUserGroup.class);
        validEntityBeforeSave(update);
        sysUserGroupMapper.updateById(update);

        // 先将组内原用户的群组信息删除
        LambdaUpdateWrapper<SysUser> userUpdateWrapper = new LambdaUpdateWrapper<>();
        userUpdateWrapper.eq(SysUser::getUserGroupId, form.getUserGroupId());
        userUpdateWrapper.set(SysUser::getUserGroupId, null);
        sysUserMapper.update(userUpdateWrapper);

        // 再将新用户的群组信息更新
        if (update != null && CollectionUtils.isNotEmpty(form.getUserIds())) {
            List<SysUser> userList = sysUserMapper.selectBatchIds(form.getUserIds());
            userList.forEach(userInfo -> userInfo.setUserGroupId(form.getUserGroupId()));
            sysUserMapper.updateBatchById(userList);
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserGroup entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除人员群组信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return sysUserGroupMapper.deleteByIds(ids) > 0;
    }
}
